﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

// 带缓存的工厂模式管理不同飞碟的生产与回收
public class DiskFactory : MonoBehaviour
{
    public GameObject diskPrefab;              // 飞碟预制
    // 生产带有基本属性的飞碟
    private List<DiskData> use;                // 正被使用的飞碟
    private List<DiskData> free;               // 空闲的飞碟

    public void Start()
    {
        use = new List<DiskData>();
        free = new List<DiskData>();
        diskPrefab = GameObject.Instantiate<GameObject>(Resources.Load<GameObject>("Prefabs/Disk"), Vector3.zero, Quaternion.identity);
        diskPrefab.SetActive(false);
    }

    // 生产飞碟
    public GameObject GetDisk(int round)
    {
        GameObject disk;
        // 如果有空闲的飞碟就直接使用，否则生成新的
        if (free.Count > 0)
        {
            disk = free[0].gameObject;
            free.Remove(free[0]);
        }
        else
        {
            disk = GameObject.Instantiate<GameObject>(diskPrefab, Vector3.zero, Quaternion.identity);
            disk.AddComponent<DiskData>();
        }

        // 飞碟的等级 = 0~2之间的随机数 * 轮次数
        // 轮次 round 越高，出的飞碟分数越高，速度也越快
        float level = UnityEngine.Random.Range(0, 2f) * (round + 1);
        if (level < 4)
        {
            disk.GetComponent<DiskData>().points = 1;
            disk.GetComponent<DiskData>().speed = 3.0f;
            disk.GetComponent<DiskData>().direction = new Vector3(UnityEngine.Random.Range(-1f, 1f) > 0 ? 2 : -2, 1, 0);
            disk.GetComponent<Renderer>().material.color = Color.white; // 白色飞碟，速度最慢
        }
        else if (level >= 4 && level < 7)
        {
            disk.GetComponent<DiskData>().points = 2;
            disk.GetComponent<DiskData>().speed = 5.0f;
            disk.GetComponent<DiskData>().direction = new Vector3(UnityEngine.Random.Range(-1f, 1f) > 0 ? 2 : -2, 1, 0);
            disk.GetComponent<Renderer>().material.color = Color.red; // 红色飞碟，速度中等
        }
        else
        {
            disk.GetComponent<DiskData>().points = 3;
            disk.GetComponent<DiskData>().speed = 7.0f;
            disk.GetComponent<DiskData>().direction = new Vector3(UnityEngine.Random.Range(-1f, 1f) > 0 ? 2 : -2, 1, 0);
            disk.GetComponent<Renderer>().material.color = Color.blue; // 蓝色飞碟，速度最快
        }

        use.Add(disk.GetComponent<DiskData>());

        return disk;
    }
  
    // 回收飞碟
    public void FreeDisk(GameObject disk)
    {
        // 找到使用中的飞碟，将其回收
        foreach (DiskData diskData in use)
        {
            if (diskData.gameObject.GetInstanceID() == disk.GetInstanceID())
            {
                disk.SetActive(false);
                free.Add(diskData);
                use.Remove(diskData);
                break;
            }

        }
    }
}
